package com.zxbit.flash.ui.activity.loan;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.CountDownTimer;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.zxbit.flash.R;
import com.zxbit.flash.adapter.PaycodeAdapter;
import com.zxbit.flash.base.BaseTitleActivity;
import com.zxbit.flash.common.Constant;
import com.zxbit.flash.common.RouterMap;
import com.zxbit.flash.mvpview.PayMethodMvpView;
import com.zxbit.flash.network.Urls;
import com.zxbit.flash.presenter.PayMethodPresenter;
import com.zxbit.flash.bean.PayCodeDataNew;
import com.zxbit.flash.response.PayCodeResponse;
import com.zxbit.flash.response.PayCodeResponseNew;
import com.zxbit.flash.utils.StringUtils;
import com.zxbit.flash.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 还款界面
 */
@SuppressLint("SetTextI18n")
@Route(name = "还款方式", path = RouterMap.REPAY_METHOD_PAGE)
public class PayMethodActivity extends BaseTitleActivity implements PayMethodMvpView, PaycodeAdapter.OnCopyListener {

    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_atm_button)
    TextView tvAtmButton;
    @BindView(R.id.ll_atm_layout)
    LinearLayout llAtmLayout;
    @BindView(R.id.ll_atm)
    LinearLayout llAtm;
    @BindView(R.id.tv_otc_button)
    TextView tvOtcButton;
    @BindView(R.id.ll_otc_layout)
    LinearLayout llOtcLayout;
    @BindView(R.id.ll_otc)
    LinearLayout llOtc;
    @BindView(R.id.tv_pay_guide)
    TextView tvPayGuide;
    @BindView(R.id.rv_atm)
    RecyclerView rvAtm;
    @BindView(R.id.rv_otc)
    RecyclerView rvOtc;
    @Autowired(name = Constant.ORDER_ID)
    String mOrderId; //订单编号
    @Autowired(name = Constant.ORDER_MONEY_NUM)
    String mOrderMoneyNum; //还款金额

    private boolean isRollover; // 目前没有展期的
    private int payType = 1;
    private PayMethodPresenter presenter;
    private CountDownTimer atmCountDownTimer, otcCountDownTimer;
    StringBuilder timeStr = new StringBuilder();

    private PaycodeAdapter atmAdapter, otcAdapter;
    private List<PayCodeDataNew.PayCodeBean> atmCodes = new ArrayList<>();
    private List<PayCodeDataNew.PayCodeBean> otcCodes = new ArrayList<>();

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
    }

    @Override
    protected void onUIReady() {
        presenter = new PayMethodPresenter(this);
        if (StringUtils.isEmpty(mOrderId) || StringUtils.isEmpty(mOrderMoneyNum)) {
            ToastUtils.showShort(this, getStringResource(R.string.incorrect_parameters));
            finish();
            return;
        }

        LinearLayoutManager layoutManager = new LinearLayoutManager(PayMethodActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvAtm.setLayoutManager(layoutManager);
        LinearLayoutManager layoutManager1 = new LinearLayoutManager(PayMethodActivity.this);
        layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
        rvOtc.setLayoutManager(layoutManager1);

        atmAdapter = new PaycodeAdapter(PayMethodActivity.this, atmCodes);
        atmAdapter.setCopyListener(this);
        rvAtm.setAdapter(atmAdapter);
        otcAdapter = new PaycodeAdapter(PayMethodActivity.this, otcCodes);
        otcAdapter.setCopyListener(this);
        rvOtc.setAdapter(otcAdapter);

        tvMoney.setText(getStringResource(R.string.money_unit_hint) + mOrderMoneyNum);

        getCode();
    }

    /**
     * 获取还款码  目前没有展期的
     */
    public void getCode() {
        if (!isRollover) {
            presenter.getPayCodeNew(mOrderId);
        } else {
            presenter.getRollovePayCode(mOrderId);
        }
        showLoadingView();
    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_pay_method;
    }

    @Override
    public String getPageTitle() {
        return getString(R.string.bill_repayment);
    }

    @OnClick({R.id.tv_pay_guide, R.id.ll_atm, R.id.ll_otc, R.id.tv_atm_button, R.id.tv_otc_button})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_pay_guide:
                //还款指南
                ARouter.getInstance().build(RouterMap.WEB_VIEW_PAGE).withString(Constant
                        .PARAMS_URL, Urls.PAY_GUIDE_URL).withInt(Constant.PARAMS_TYPE, Constant.WEB_TYPE_GUIDE).navigation();
                break;
            case R.id.ll_atm:
                payType = 1;
                showCode();
                break;
            case R.id.ll_otc:
                payType = 2;
                showCode();
                break;
            case R.id.tv_atm_button:
                getCode();
                break;
            case R.id.tv_otc_button:
                getCode();
                break;
        }
    }

    @Override
    public void onCopyClick(TextView view) {
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        cm.setPrimaryClip(ClipData.newPlainText("text", view.getText().toString()));
        if (cm.hasPrimaryClip()) {
            cm.getPrimaryClip().getItemAt(0).getText();
        }
        ToastUtils.showShort(PayMethodActivity.this, getStringResource(R.string.help_center_copy_succeed));
    }

    @Override
    public void onGetDataNext(PayCodeResponse payCodeResponse) {}

    @Override
    public void onGetDataError(Throwable throwable) {
        dismissLoadingView();
    }

    private String getFormatTime(long millisUntilFinished) {
        timeStr.delete(0, timeStr.length());

        if (millisUntilFinished < 0) return "";
        Long day = millisUntilFinished / (1000 * 60 * 60 * 24);   //以天数为单位取整
        Long hour = (millisUntilFinished / (60 * 60 * 1000) - day * 24);    //以小时为单位取整
        Long min = ((millisUntilFinished / (60 * 1000)) - day * 24 * 60 - hour * 60); //以分钟为单位取整
        Long second = (millisUntilFinished / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min *
                60);//秒

        if (day > 0) {
            timeStr.append(day).append(":");
        }
        if (hour > 0 || (hour == 0 && timeStr.length() > 0)) {
            timeStr.append(hour).append(":");
        }
        if (min > 0 || (min == 0 && timeStr.length() > 0)) {
            timeStr.append(min).append(":");
        }
        timeStr.append(second);

        return timeStr.toString();
    }

    /**
     * 获取还款码
     *
     * @param response
     */
    @Override
    public void onGetDataNext(PayCodeResponseNew response) {
        dismissLoadingView();
        if (response.getStatus() == Constant.HTTP_OK) {
            if (response.hasData() && response.getData().size() > 0) {
                ArrayList<PayCodeDataNew> list = response.getData();
                for (PayCodeDataNew payCodeDataNew : list) {
                    if (payCodeDataNew.getType().equals("ATM")) {
                        //过期时间的
                        atmCountDownTimer = new CountDownTimer(Long.parseLong(payCodeDataNew
                                .getExpire()), 1000) {

                            @Override
                            public void onTick(long millisUntilFinished) {
                                tvAtmButton.setText(getString(R.string.pay_code_reget) + " " +
                                        getFormatTime(millisUntilFinished));
                            }

                            @Override
                            public void onFinish() {
                                tvAtmButton.setClickable(true);
                                tvAtmButton.setBackgroundResource(R.drawable.button_no_click);
                                tvAtmButton.setText(R.string.retry_acquire);
                            }
                        };
                        atmCodes = payCodeDataNew.getVouchers();
                        atmCountDownTimer.start();
                        tvAtmButton.setClickable(false);
                    } else if (payCodeDataNew.getType().equals("OTC")) {
                        otcCodes = payCodeDataNew.getVouchers();
                        otcCountDownTimer = new CountDownTimer(Long.parseLong(payCodeDataNew
                                .getExpire()), 1000) {
                            @Override
                            public void onTick(long millisUntilFinished) {
                                tvOtcButton.setText(getString(R.string.pay_code_reget) + " " +
                                        getFormatTime(millisUntilFinished));
                            }

                            @Override
                            public void onFinish() {
                                tvOtcButton.setClickable(true);
                                tvOtcButton.setBackgroundResource(R.drawable.button_no_click);
                                tvOtcButton.setText(R.string.retry_acquire);
                            }
                        };
                        otcCountDownTimer.start();
                        tvOtcButton.setClickable(false);
                    }
                }
            }
            showCode();
        }
    }

    /**
     * 展示code
     */
    private void showCode() {
        if (1 == payType) {
            llAtmLayout.setVisibility(View.VISIBLE);
            llOtcLayout.setVisibility(View.GONE);

            atmAdapter.setData(atmCodes);
            atmAdapter.notifyDataSetChanged();

        } else {
            llAtmLayout.setVisibility(View.GONE);
            llOtcLayout.setVisibility(View.VISIBLE);

            otcAdapter.setData(otcCodes);
            otcAdapter.notifyDataSetChanged();

        }
    }
}
